package chapter1.fundamentals.exercise;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;

import java.util.Arrays;

/**
 * @author quanlinlin on 2018/10/25 9:07.
 * @version 1.0
 */
public class E_29 {


    public static void main(String[] args) {
        int[] whitelist = In.readInts(args[0]);


        Arrays.sort(whitelist);
        for (int i : whitelist) {
            System.out.print(i + "\t");
        }
        System.out.println();

        // read key; print if not in whitelist
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            System.out.println(key + ":" + rankRecur(key, whitelist));
        }

    }

    /**
     * 返回key元素在白名单中的最低排名，白名单数组有序且可能有重复元素
     *
     * @param key
     * @param whitelist
     * @return
     */
    public static int rankRecur(int key, int... whitelist) {
        int lo = 0;
        int hi = whitelist.length - 1;
        return rankRecur(key, whitelist, lo, hi);
    }

    private static int rankRecur(int key, int[] whitelist, int lo, int hi) {
        if (lo > hi) {
            return -1;
        }

        int mid = lo + (hi - lo) / 2;

        if (key < whitelist[mid]) {
            return rankRecur(key, whitelist, lo, mid - 1);
        } else if (key > whitelist[mid]) {
            return rankRecur(key, whitelist, lo + 1, hi);
        } else {
            if (mid == 0) {
                return 0;
            }
            if (whitelist[mid - 1] < key) {
                return mid;
            }
            return rankRecur(key, whitelist, lo, mid);
        }
    }

    public static int countRecur(int key, int[] whitelist) {
        int lo = rankRecur(key, whitelist);
        int count = 0;
        for (int i = lo; i < whitelist.length; i++) {
            if (key == whitelist[i]) {
                count++;
            }
        }
        return count;
    }

    /**
     * 迭代式二分查找
     *
     * @param key
     * @param whitelist
     * @return
     */
    private static int rankIter(int key, int[] whitelist) {
        int lo = 0;
        int hi = whitelist.length - 1;
        int mid;
        while (lo <= hi) {
            mid = lo + (hi - lo) / 2;
            if (key > whitelist[mid]) {
                lo = mid + 1;
            } else if (key < whitelist[mid]) {
                hi = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    /**
     * 返回key元素在白名单中出现的次数
     *
     * @param key
     * @param whitelist
     * @return
     */
    private static int count(int key, int... whitelist) {
        return 0;
    }
}
